package longrise.phone.com.bjjt_jyb.Utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.czt.mp3recorder.Mp3Recorder;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 录音操作的辅助类
 */
public class RecordHelper {
    private Context context;

    private Timer timer;// 定时器

    private TimerTask task;

    public ImageView getMyrecord_iv_record() {
        return myrecord_iv_record;
    }

    public void setMyrecord_iv_record(ImageView myrecord_iv_record) {
        this.myrecord_iv_record = myrecord_iv_record;
    }

    private ImageView myrecord_iv_record;
    public ImageView getMyPlayIV() {
        return myPlayIV;
    }

    public void setMyPlayIV(ImageView myPlayIV) {
        this.myPlayIV = myPlayIV;
    }

    private ImageView myPlayIV;//播放按钮

    public RecordViewManager.recordOver getmRecordOver() {
        return mRecordOver;
    }

    public void setmRecordOver(RecordViewManager.recordOver mRecordOver) {
        this.mRecordOver = mRecordOver;
    }

    private RecordViewManager.recordOver mRecordOver;

    public Button getMyRecordBtn() {
        return myRecordBtn;
    }

    public void setMyRecordBtn(Button myRecordBtn) {
        this.myRecordBtn = myRecordBtn;
    }

    private Button myRecordBtn;

    /********************* 播放录音相关 *************************************/

    /**
     * 录音播放控制开关
     */
    private boolean isPlaying = false;

    private MediaPlayer mPlayer;

    /**
     * 录音播放的标识
     */
    public static final int PLAY = 0;

    /**
     * 录音结束的监听
     */
    private onPlayFinishListener playListener;

    /********************* 录音相关 *************************************/

    /**
     * 录音的标识
     */
    public static final int RECORD = 1;

    private Mp3Recorder mRecorder;

    /**
     * 录音结束的监听
     */
    private onRecordFinishListener listener;

    /**
     * 录音的时间
     */
    private int recordTime;

    private String recordPath;

    /**
     * 是否正在录音
     */
    private boolean isRecord = false;

    private static RecordHelper instance;

    private RecordHelper(Context context) {
        this.context = context.getApplicationContext();
    }

    public static RecordHelper getInstance(Context activity) {
        if (instance == null) {
            synchronized (RecordHelper.class) {
                instance = new RecordHelper(activity);
            }
        }
        return instance;
    }

    public boolean isPlaying() {
        return isPlaying;
    }

    /**
     * 开始录音
     */
    public void startRecord(String filePath) {
        try {
            if (filePath == null) {
                Toast.makeText(context, "录音保存路径有误", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isRecord) {
                // 初始化录音类开始录音
                mRecorder = new Mp3Recorder();
                // 判断和创建文件夹
                File file = new File(filePath);
                file.createNewFile();// 创建文件

                mRecorder.startRecording(filePath);
                isRecord = true;
                this.recordPath = filePath;

                startTimer(RECORD);
            }
        } catch (Exception e) {
            e.printStackTrace();
            finishRecord();
            Toast.makeText(context, "录音无法打开，请检查权限", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 播放录音
     *
     * @param filePath
     */
    public void playRecord(String filePath) {
        if (filePath == null) {
            Toast.makeText(context, "录音路径有问题", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            if (!isPlaying) {// 未播放
                mPlayer = MediaPlayer.create(context, Uri.parse(filePath));
                mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {// 音频播放结束事件
                    @Override
                    public void onCompletion(MediaPlayer arg0) {
                        stopMPlayer();
                    }
                });
                mPlayer.start();
                isPlaying = true;
            } else {//停止录音
                stopMPlayer();
            }
        } catch (Exception e) {
            e.printStackTrace();
            stopMPlayer();
            Toast.makeText(context, "文件或音频出现问题", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 关闭录音
     */
    public void stopMPlayer() {
        try {
            if (isPlaying) {
                if (playListener != null) {
                    playListener.playFinish();
                }
                isPlaying = false;
            }
            // 关闭播放器
            if (mPlayer.isPlaying()) {
                mPlayer.stop();
            }
            mPlayer.reset();
            mPlayer.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mPlayer = null;
            isPlaying = false;
        }
    }

    /**
     * 结束录音(注意同时执行两次的情况)
     */
    public void finishRecord() {
        try {
            if (isRecord) {
                if (listener != null) {
                    listener.recordFinish(recordTime, recordPath);
                }
                isRecord = false;
            }
            myRecordBtn.setText("现场录音");
            //mRecordBtn.setBackgroundResource(R.drawable.record_btn_normal_bg);
            //startRecord = false;
            mRecordOver.onRecordOver();

            //myRecordBtn.setOnClickListener(RecordViewManager.this);//录制完成才能点击重新录制

            stopTimer();
            stopRecorder();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            isRecord = false;
        }
    }

    /**
     * 关闭录音类
     */
    private void stopRecorder() {
        try {
            if (mRecorder != null) {
                mRecorder.stopRecording();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mRecorder = null;
        }
    }

    /**
     * 启动定时器
     */
    private void startTimer(final int action) {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                recordTime++;// 增加录音时间
                handler.sendEmptyMessage(action);
            }
        };
        // 每隔1秒更新一次界面
        timer.schedule(task, 0, 1000);
    }

    /**
     * 关闭定时器
     */
    private void stopTimer() {
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        recordTime = 0;// 重置录音时间
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case RECORD:// 记录录音进度
                        if (recordTime > 120) {// 大于120秒则自动结束录音
                            finishRecord();
                            myPlayIV.setVisibility(View.VISIBLE);
                            Toast.makeText(context, "录音已经自动保存", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
                super.handleMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void setOnRecordFinishListener(onRecordFinishListener listener) {
        this.listener = listener;
    }

    public void setOnPlayFinishListener(onPlayFinishListener listener) {
        this.playListener = listener;
    }

    /**
     * 录音结束的监听接口
     */
    public interface onRecordFinishListener {
        /**
         * 录音结束的回调方法
         */
        void recordFinish(int time, String path);
    }

    /**
     * 播放音频结束的监听接口
     */
    public interface onPlayFinishListener {
        /**
         * 播放结束的回调方法
         */
        void playFinish();
    }
}
